package org.totoro;

import org.apache.commons.net.telnet.TelnetClient;

import java.io.*;

/**
 * Hello world!
 */
public class App {

    public static void main(String[] args) throws IOException, InterruptedException {

        TelnetClient tc = new TelnetClient();
        tc.connect("10.23.229.102", 20880);
        //tc.connect("10.23.229.102:", 20880);
        InputStream in = tc.getInputStream();
        OutputStream os = tc.getOutputStream();

        readUntil(in);

        writeUtil("\n", os);

        for (int i = 0; i < 100000; i++) {
            writeUtil("status -l", os);
            Thread.sleep(1000);
        }





    }

    /**
     * 写入命令方法
     *
     * @param cmd
     * @param os
     */
    public static void writeUtil(String cmd, OutputStream os) {
        try {
            cmd = cmd + "\n";
            os.write(cmd.getBytes());
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 读到指定位置,不在向下读
     *
     * @param in
     * @return
     */
    public static void readUntil(InputStream in) {

        new Thread(new Runnable() {
            @Override
            public void run() {

                InputStreamReader isr = new InputStreamReader(in);

                char[] charBytes = new char[1024];
                int n = 0;
                boolean flag = false;

                try {
                    while ((n = isr.read(charBytes)) != -1) {
                        String str = "";
                        for (int i = 0; i < n; i++) {
                            char c = (char) charBytes[i];
                            str += c;

                        }

                        System.out.println(str);

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

}
